var express = require('express');
var router = express.Router();
var file = require('../db/muitiparty');
var config = require('../config');
var fs =require('fs');
var Promise = require('promise');
var crypto = require('crypto');
var keep = require('../db/keep');
var VandB = require('../db/VandB');

/* GET users listing. */
router.get('/', function(req,res,next) {
	
	req.VandB.count({'upUser':req.infos._id+""},function(err,result){
		if (!req.cookies.recc) {
			res.redirect('/log/login')
		} else {
			res.render('user',{'title':'个人中心','user':req.infos,'count':result});
		}
	});

});

router.get('/sign',function(req,res,next) {
	if (!req.cookies.recc) {
		res.redirect('/log/login')
	} else {
		if (!req.infos.sign || req.infos.sign=='') {
			var sign = new Date().getTime();
			var LV = req.infos.LV;
			LV += 15;

			var data = {
				'sign':sign,
				'LV':LV,
			}

			req.users.updateById(req.infos._id,{$set:data},function(err, result){
				if (err) {
					res.send('err');
				} else {
					res.send('ok');
				}
			});
		} else {
			var oldSign = new Date(req.infos.sign);
			var sign = new Date();
			var isSign = true;
			if (oldSign.getFullYear() == sign.getFullYear() && oldSign.getMonth() == sign.getMonth() && oldSign.getDate() == sign.getDate()) {
				isSign = false;
			}
			if(isSign){
				sign = sign.getTime();
				var LV = req.infos.LV;
				LV += 10;

				var data = {
					'sign':sign,
					'LV':LV,
				}

				req.users.updateById(req.infos._id,{$set:data},function(err, result){
					if (err) {
						res.send('err');
					} else {
						res.send('ok');
					}
				});
			} else {
				res.send('no');
			}
		}
	}
});

router.get('/myself', function(req,res,next) {
	if (!req.cookies.recc) {
		res.redirect('/log/login')
	} else {
		res.render('myself',{'title':' 我的信息 ','user':req.infos});
	}
});

router.post('/myself',function(req,res,next) {
	var motto = req.body.usermotto;
	motto = motto.replace(/</g,"&lt;");
	motto = motto.replace(/>/g,"&gt;");
	var data = {
		'motto':motto,
		'sex': req.body.sex,
	}



	req.users.updateById(req.infos._id,{$set:data},function(err, result){
		if (err) {
			res.redirect('/');
		} else {
			res.redirect('/user');
		}
	});
});

router.put('/myself/head', function(req, res, next){

	var base64Img = req.body.imgPath
	base64Img = base64Img.replace(/^data:image\/\w+;base64,/, "");

	var dataBuffer = new Buffer(base64Img, 'base64')
	fs.writeFile(config.USERPATH+req.body.user.userid+'.png', dataBuffer, function(err){
		if (err) {

		} else {
			req.users.updateById(req.infos._id,{
				$set:{
					'headImgUrl':'/user/'+req.body.user.userid+'.png'
				}
			}, function(err, result){
				if (err) {} else {
					res.json({headImgUrl:'/user/'+req.body.user.userid+'.png'});
				}
			})
		}
	})
})



router.post('/userhead', function(req, res, next){
	try{
		fs.unlinkSync(__dirname +'/../public'+req.infos.headImgUrl);
		file.newFiles(req,config.USERPATH, function(date){
			res.json(date);
		}, function jindu(status){
			req.session.headprogress = status;
		})
	}catch(e){

	}
});

router.get('/userhead/ajax', function(req, res, next){
	res.json({'progress':req.session.headprogress})
});


router.get('/upvideo', function(req, res, next) {
	try{
		if (!req.cookies.recc) {
			res.redirect('/log/login')
		} else {
			res.render('upVideo',{
				'title':'up video',
				'user':req.infos,
				'action':'videofile'
			})
		}
	} catch (e){

	}
});

router.post('/videofile', function(req, res, next){
	req.session.jin = 0
	file.newFiles(req, config.PATH, function(date){
		res.json(date)
	}, function jindu(status){
		req.session.jin = status;
	})
})

router.get('/videofile/ajax', function(req, res, next){
	res.json({'jin':req.session.jin})
})

router.post('/videofile/ajaxInfo', function(req, res, next){
	var imgname = req.body.videoPath
	imgname = imgname.replace(/.mp4/,'.png');

	var base64Img = req.body.imgPath
	base64Img = base64Img.replace(/^data:image\/\w+;base64,/, "");

	var dataBuffer = new Buffer(base64Img, 'base64')
	fs.writeFile(config.PATH+imgname, dataBuffer, function(err){
		if (err) {
			res.send(err)
		} else {
			req.VandB.insert({
				'type':'video',
				'pass':false,
				'name':req.body.vName,
				'info':req.body.vInfo,
				'tag' :req.body.tag,
				'path':req.body.videoPath,
				'img' :imgname,
				'upUser'   :req.body.user.userid,
				'upTime'   :new Date().getTime()
			}, function(err, result){
				if (err) {
					
				} else {
					res.send('ok')
				}
			})
		}
	})
})

router.get('/video/list', function(req, res, next){
	try{
		req.VandB.find({
			'type':'video',
			'upUser':req.infos._id
		}, function(err, result){
			if (err) {
				res.status(400).render('404',{})
			} else {
				res.render('list',{
					'title':'文章',
					'user':req.infos,
					'articles':'',
					'video':result
				})
			}
		})
	} catch(e){

	}
})


router.get('/message', function(req, res, next) {
	if (!req.cookies.recc) {
			res.redirect('/log/login')
	} else {
		
		req.users.find({"_id":{$in:req.infos.record}}).toArray(function(err,items) {
			if(items == null )
			items = [];
			res.render('message',{'title':'我的私信','user':req.infos,'upUser':'','ups':items});
		});
	}
});

router.get('/message/:id', function(req, res, next) {
	if (!req.cookies.recc) {
			res.redirect('/log/login')
	} else {
		req.users.find({"_id":{$in:req.infos.record}}).toArray(function(err,items) {
			if(items == null )
			items = [];
			var ups = items;
			req.users.findById(req.params.id, function(err, result) {
				res.render('message',{'title':'我的私信','user':req.infos,'upUser':result,'ups':ups});
			});
		});
	}
});


router.post('/message/record',function(req,res,next) {

	var insert = {
		'userid':req.body.record.userid,
		'toid':req.body.record.toid,
		'content':req.body.record.content,
		'upTime':new Date().getTime(),
	}

	req.record.insert(insert, function(err, result){
		req.users.update({'_id':req.dbid(req.body.record.userid)},
					{$addToSet:{'record':req.dbid(req.body.record.toid)}},
					function(err, result){
						req.users.update({'_id':req.dbid(req.body.record.toid)},
						{$addToSet:{'record':req.dbid(req.body.record.userid)}},
						function(err, result){
							res.send("ok");
						})
					})
	})

});

router.post('/message/getrec',function(req,res,next){

	req.record.find({$or:[{'userid':req.infos._id+"",'toid':req.body.getrec.toid},
						  {'userid':req.body.getrec.toid,'toid':req.infos._id+""}]}).sort({'upTime':1}).toArray(function(err,items) {
			if (err) {
				callback('bad request')
			} else {

				res.send(items);
			}
	});
});

router.delete('/message/reuser/:id',function(req,res,next){

	req.users.update({"_id":req.infos._id},{$pull:{'record':req.dbid(req.params.id)}},
	function(err, result){
		res.send("ok");
	})

});


router.get('/keep', function(req, res, next){
	try{
		var Arr = new Array()
		for (var i = 0; i < req.infos.keepAV.length; i++) {
			Arr.push(req.infos.keepAV[i].avid)
		}
		for (var i = 0; i < req.infos.keepAT.length; i++) {
			Arr.push(req.infos.keepAT[i].avid)
		}
		VandB.findArr(req, Arr, function(d){
			res.send(d)
		})
	}catch(e){
		
	}
})

module.exports = router;
